/**
 *  日期处理工具类
 *  @Authors: LiRui
 *  @date 2017-09-13
 *
 */
var DateUtils = {
    patterns: {
        PATTERN_ERA: 'G', //Era 标志符 Era strings. For example: "AD" and "BC"
        PATTERN_YEAR: 'y', //年
        PATTERN_MONTH: 'M', //月份
        PATTERN_DAY_OF_MONTH: 'd', //月份的天数
        PATTERN_HOUR_OF_DAY1: 'k', //一天中的小时数（1-24）
        PATTERN_HOUR_OF_DAY0: 'H', //24小时制，一天中的小时数（0-23）
        PATTERN_MINUTE: 'm', //小时中的分钟数
        PATTERN_SECOND: 's', //秒
        PATTERN_MILLISECOND: 'S', //毫秒
        PATTERN_DAY_OF_WEEK: 'E', //一周中对应的星期，如星期一，周一
        PATTERN_DAY_OF_YEAR: 'D', //一年中的第几天
        PATTERN_DAY_OF_WEEK_IN_MONTH: 'F', //一月中的第几个星期(会把这个月总共过的天数除以7,不够准确，推荐用W)
        PATTERN_WEEK_OF_YEAR: 'w', //一年中的第几个星期
        PATTERN_WEEK_OF_MONTH: 'W', //一月中的第几星期(会根据实际情况来算)
        PATTERN_AM_PM: 'a', //上下午标识
        PATTERN_HOUR1: 'h', //12小时制 ，am/pm 中的小时数（1-12）
        PATTERN_HOUR0: 'K', //和h类型
        PATTERN_ZONE_NAME: 'z', //时区名
        PATTERN_ZONE_VALUE: 'Z', //时区值
        PATTERN_WEEK_YEAR: 'Y', //和y类型
        PATTERN_ISO_DAY_OF_WEEK: 'u',
        PATTERN_ISO_ZONE: 'X'
    },
    week: {
        'ch': {
            "0": "\u65e5",
            "1": "\u4e00",
            "2": "\u4e8c",
            "3": "\u4e09",
            "4": "\u56db",
            "5": "\u4e94",
            "6": "\u516d"
        },
        'en': {
            "0": "Sunday",
            "1": "Monday",
            "2": "Tuesday",
            "3": "Wednesday",
            "4": "Thursday",
            "5": "Friday",
            "6": "Saturday"
        }
    },
    //获取当前时间
    getCurrentTime: function () {
        var today = new Date();
        var year = today.getFullYear();
        var month = today.getMonth() + 1;
        var day = today.getDate();
        var hours = today.getHours();
        var minutes = today.getMinutes();
        var seconds = today.getSeconds();
        var timeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        return timeString;
    },
    /**
     * 比较时间大小
     * time1>time2 return 1
     * time1<time2 return -1
     * time1==time2 return 0
     */
    compareTime: function (time1, time2) {
        if (Date.parse(time1.replace(/-/g, "/")) > Date.parse(time2.replace(/-/g, "/"))) {
            return 1;
        } else if (Date.parse(time1.replace(/-/g, "/")) < Date.parse(time2.replace(/-/g, "/"))) {
            return -1;
        } else if (Date.parse(time1.replace(/-/g, "/")) == Date.parse(time2.replace(/-/g, "/"))) {
            return 0;
        }
    },
    //是否闰年
    isLeapYear: function (year) {
        return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
    },
    //获取某个月的天数，从0开始
    getDaysOfMonth: function (year, month) {
        return [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month-1];
    },
    getDaysOfMonth2: function (year, month) {
        // 将天置为0，会获取其上个月的最后一天
        month = parseInt(month) + 1;
        var date = new Date(year, month, 0);
        return date.getDate();
    },
    /**
     * 距离现在几天的日期：负数表示今天之前的日期，0表示今天，整数表示未来的日期
     * 如-1表示昨天的日期，0表示今天，2表示后天
     */
    fromToday: function (days) {
        var today = new Date();
        today.setDate(today.getDate() + days);
        var date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
        return date;
    },
    /**
     * 日期后几天的日期
     */
    fromDay: function (today, days) {
        today = new Date(today);
        today.setDate(today.getDate() + days);
        var date = today.getFullYear() + "-" + (today.getMonth() + 1) + "-" + today.getDate();
        return date;
    },
    /*    /!**
         * 日期时间格式化
         * @param {Object} dateTime 需要格式化的日期时间
         * @param {String} pattern  格式化的模式，如yyyy-MM-dd hh(HH):mm:ss.S a k K E D F w W z Z
         *!/
        formt: function(dateTime, pattern) {
            var date = new Date(dateTime);
            if(Bee.StringUtils.isBlank(pattern)) {
                return date.toLocaleString();
            }
            return pattern.replace(/([a-z])\1*!/ig, function(matchStr, group1) {
                var replacement = "";
                switch(group1) {
                    case Bee.DateUtils.patterns.PATTERN_ERA: //G
                        break;
                    case Bee.DateUtils.patterns.PATTERN_WEEK_YEAR: //Y
                    case Bee.DateUtils.patterns.PATTERN_YEAR: //y
                        replacement = date.getFullYear();
                        break;
                    case Bee.DateUtils.patterns.PATTERN_MONTH: //M
                        var month = date.getMonth() + 1;
                        replacement = (month < 10 && matchStr.length >= 2) ? "0" + month : month;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_DAY_OF_MONTH: //d
                        var days = date.getDate();
                        replacement = (days < 10 && matchStr.length >= 2) ? "0" + days : days;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_HOUR_OF_DAY1: //k(1~24)
                        var hours24 = date.getHours();
                        replacement = hours24;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_HOUR_OF_DAY0: //H(0~23)
                        var hours24 = date.getHours();
                        replacement = (hours24 < 10 && matchStr.length >= 2) ? "0" + hours24 : hours24;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_MINUTE: //m
                        var minutes = date.getMinutes();
                        replacement = (minutes < 10 && matchStr.length >= 2) ? "0" + minutes : minutes;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_SECOND: //s
                        var seconds = date.getSeconds();
                        replacement = (seconds < 10 && matchStr.length >= 2) ? "0" + seconds : seconds;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_MILLISECOND: //S
                        var milliSeconds = date.getMilliseconds();
                        replacement = milliSeconds;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_DAY_OF_WEEK: //E
                        var day = date.getDay();
                        replacement = Bee.DateUtils.week['ch'][day];
                        break;
                    case Bee.DateUtils.patterns.PATTERN_DAY_OF_YEAR: //D
                        replacement = Bee.DateUtils.dayOfTheYear(date);
                        break;
                    case Bee.DateUtils.patterns.PATTERN_DAY_OF_WEEK_IN_MONTH: //F
                        var days = date.getDate();
                        replacement = Math.floor(days / 7);
                        break;
                    case Bee.DateUtils.patterns.PATTERN_WEEK_OF_YEAR: //w
                        var days = Bee.DateUtils.dayOfTheYear(date);
                        replacement = Math.ceil(days / 7);
                        break;
                    case Bee.DateUtils.patterns.PATTERN_WEEK_OF_MONTH: //W
                        var days = date.getDate();
                        replacement = Math.ceil(days / 7);
                        break;
                    case Bee.DateUtils.patterns.PATTERN_AM_PM: //a
                        var hours24 = date.getHours();
                        replacement = hours24 < 12 ? "\u4e0a\u5348" : "\u4e0b\u5348";
                        break;
                    case Bee.DateUtils.patterns.PATTERN_HOUR1: //h(1~12)
                        var hours12 = date.getHours() % 12 || 12; //0转为12
                        replacement = (hours12 < 10 && matchStr.length >= 2) ? "0" + hours12 : hours12;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_HOUR0: //K(0~11)
                        var hours12 = date.getHours() % 12;
                        replacement = hours12;
                        break;
                    case Bee.DateUtils.patterns.PATTERN_ZONE_NAME: //z
                        replacement = Bee.DateUtils.getZoneNameValue(date)['name'];
                        break;
                    case Bee.DateUtils.patterns.PATTERN_ZONE_VALUE: //Z
                        replacement = Bee.DateUtils.getZoneNameValue(date)['value'];
                        break;
                    case Bee.DateUtils.patterns.PATTERN_ISO_DAY_OF_WEEK: //u
                        break;
                    case Bee.DateUtils.patterns.PATTERN_ISO_ZONE: //X
                        break;
                    default:
                        break;
                }
                return replacement;
            });
        },*/
    /**
     * 计算一个日期是当年的第几天
     * @param {Object} date
     */
    dayOfTheYear: function (date) {
        var obj = new Date(date);
        var year = obj.getFullYear();
        var month = obj.getMonth(); //从0开始
        var days = obj.getDate();
        var daysArr = [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        for (var i = 0; i < month; i++) {
            days += daysArr[i];
        }
        return days;
    },
    //获得时区名和值
    getZoneNameValue: function (dateObj) {
        var date = new Date(dateObj);
        date = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
        var arr = date.toString().match(/([A-Z]+)([-+]\d+:?\d+)/);
        var obj = {
            'name': arr[1],
            'value': arr[2]
        };
        return obj;
    },
    /**
     * 得到日期在一年当中的周数
     */
    getISOYearWeek: function (date) {
        var commericalyear = this.getCommerialYear(date);
        var date2 = this.getYearFirstWeekDate(commericalyear);
        var day1 = date.getDay();
        if (day1 == 0) day1 = 7;
        var day2 = date2.getDay();
        if (day2 == 0) day2 = 7;
        var d = Math.round((date.getTime() - date2.getTime() + (day2 - day1) * (24 * 60 * 60 * 1000)) / 86400000);
        return Math.floor(d / 7) + 1;
    },
    /**
     * 得到一年之中的第一周的日期
     */
    getYearFirstWeekDate: function (commericalyear) {
        var yearfirstdaydate = new Date(commericalyear, 0, 1);
        var daynum = yearfirstdaydate.getDay();
        var monthday = yearfirstdaydate.getDate();
        if (daynum == 0) daynum = 7;
        if (daynum <= 4) {
            return new Date(yearfirstdaydate.getFullYear(), yearfirstdaydate.getMonth(), monthday + 1 - daynum);
        } else {
            return new Date(yearfirstdaydate.getFullYear(), yearfirstdaydate.getMonth(), monthday + 8 - daynum);
        }
    },
    /**
     * 获取当前日期的年份
     */
    getCommerialYear: function (date) {
        var daynum = date.getDay();
        var monthday = date.getDate();
        if (daynum == 0) daynum = 7;
        var thisthurdaydate = new Date(date.getFullYear(), date.getMonth(), monthday + 4 - daynum);
        return thisthurdaydate.getFullYear();
    },
    /**
     * 获取周一
     */
    getWeekStartDate: function (date) {
        var nowDayOfWeek = (date.getDay() == 0) ? 6 : date.getDay() - 1;
        var t = new Date(date); //复制并操作新对象，避免改动原对象
        //t.setDate(t.getDate() - nowDayOfWeek);
        t.setTime(t.getTime() - nowDayOfWeek * 86400000);
        return t;
    },
    /**
     * 获取周日。本周一+6天
     */
    getWeekEndDate: function (date) {
        var t = new Date(date); //复制并操作新对象，避免改动原对象
        //t.setDate(this.getWeekStartDate(date).getDate() + 6); //date来计算会有出错的情况出现比如10.1这一周
        t.setTime(this.getWeekStartDate(date).getTime() + 6 * 86400000);
        return t;
    },
    /**
     * 日期格式化，第一个参数为日期，第二个参数为日期格式化的格式，返回一个格式化后的字符串
     */
    dateFormat: function (date, format) {
        var o = {
            "M+": date.getMonth() + 1, //month
            "d+": date.getDate(), //day
            "h+": date.getHours(), //hour
            "m+": date.getMinutes(), //minute
            "s+": date.getSeconds(), //second
            "q+": Math.floor((date.getMonth() + 3) / 3), //quarter
            "S": date.getMilliseconds() //millisecond
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    },
    /**
     * 判断输入的日期格式是否为 yyyy-mm-dd 或 yyyy-m-d
     */
    isDate: function (dateString) {
        //判断日期是否为空
        if (dateString.trim() == "") {
            alert("日期为空！请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2013-08-08\n\r");
            return false;
        } else {
            dateString = dateString.trim();
        }

        //年月日正则表达式
        var r = dateString.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
        if (r == null) {
            alert("请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2013-08-08\n\r");
            return false;
        }
        var d = new Date(r[1], r[3] - 1, r[4]);
        var num = (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]);
        if (num == 0) {
            alert("请输入格式正确的日期\n\r日期格式：yyyy-mm-dd\n\r例    如：2013-08-08\n\r");
        }
        return (num != 0);

    },

    // 日期工具，在日期上加几天，dayNumber传天数
    addDay: function (dayNumber, date) {
        date = date ? date : new Date();
        var ms = dayNumber * (1000 * 60 * 60 * 24);
        var mydate = new Date(date.getTime() + ms);
        var str = mydate.getFullYear() + "-";
        var month = mydate.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        str += month + "-";
        var day = mydate.getDate();
        if (day < 10) {
            day = "0" + day;
        }
        str += day;
        return str;
    },

    // 获取指定日期的后一天
    getNextDay: function (d) {
        d = new Date(d);
        d = +d + 1000 * 60 * 60 * 24;
        d = new Date(d);
        var month = d.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        var day = d.getDate();
        if (day < 10) {
            day = "0" + day;
        }
        //格式化
        return d.getFullYear() + "-" + month + "-" + day;
    },

    // 计算天数差的函数，通用
    dateDiff: function (sDate1, sDate2) {
        //sDate1和sDate2是2017-01-01
        var aDate, oDate1, oDate2, iDays;
        aDate = sDate1.split("-");
        oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);    //转换为12-18-2002格式
        aDate = sDate2.split("-");
        oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
        iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24);   //把相差的毫秒数转换为天数
        return iDays;
    },

    // 计算一组日期是否连续，将连续的日期放到一个数组
    getAreaArr: function (Arr) {
        var r = [];
        for (var i = 0; i < Arr.length; i++) {
            if (getNextDay(Arr[i]) != Arr[i + 1]) {
                r.push(Arr.slice(0, i + 1));
                Arr.splice(0, i + 1);
                i = i - (i + 1);
            }
        }
        return r;
    },

    // 计算天数差的函数，包含两端日期
    dateDiffInClude: function (sDate1, sDate2) {
        //sDate1和sDate2是2017-01-01
        return parseInt(DateUtils.dateDiff(sDate1, sDate2)) + 1;
    },

    // 获取两个日期间的日期
    getDateArr: function (sDate, eDate) {
        var res = new Array();
        var startTime = getDate(sDate);
        var endTime = getDate(eDate);
        while ((endTime.getTime() - startTime.getTime()) >= 0) {
            var year = startTime.getFullYear();
            var month = startTime.getMonth().toString().length == 1 ? "0" + startTime.getMonth().toString() : startTime.getMonth();
            var day = startTime.getDate().toString().length == 1 ? "0" + startTime.getDate() : startTime.getDate();
            res.push(year + "-" + month + "-" + day);
            startTime.setDate(startTime.getDate() + 1);
        }
        return res;
    },

    // 获取日期对象
    getDate: function (datestr) {
        var temp = datestr.split("-");
        var date = new Date(temp[0], temp[1], temp[2]);
        return date;
    },

    // 获取一个日期N年后的日期，并实现减1天
    getNextNYearDate: function (date, years) {

        var now = new Date(date)
        now.setFullYear(now.getFullYear() + years);
        var newDate = DateUtils.addDay(-1, now);
        return newDate;


       /*
        var leap = 0;
        var rDate = date;

        var s = parseInt(date.substring(0, 4)) - 1;
        var e = parseInt(date.substring(0, 4)) + years + 1;
        if (DateUtils.isLeapYear(date.substring(0, 4)) == true && parseInt(date.substring(5, 7)) < 2) {
            s = parseInt(date.substring(0, 4));
        }
        if (DateUtils.isLeapYear(date.substring(0, 4) + years) == true && parseInt(date.substring(5, 7)) > 2) {
            e = parseInt(date.substring(0, 4) + years);
        }

        for (var i = s; i < e; i++) {
            var flag = DateUtils.isLeapYear(i);
            if (flag) {
                leap++;
            }
        }
        rDate = DateUtils.addDay(365 * parseInt(years) + leap - 2, new Date(date));
        return rDate;*/
    },

    // 获取一个日期N年后的日期
    getAddNYearDate: function (date, years) {
        var now = new Date(date)
        now.setFullYear(now.getFullYear() + years);
        return DateUtils.dateFormat(now, "yyyy-MM-dd");
    },

    // 获取两个日期之间相差的年数(日期相同算两年)
    getYearsDiff: function (sDate, eDate) {
        var days = DateUtils.dateDiff(sDate, eDate) + 1;

        var leap = 0;
        // var sm = sDate.substring(5, 7);
        // var em = eDate.substring(5, 7);
        var s = parseInt(sDate.substring(0, 4));
        var e = parseInt(eDate.substring(0, 4));

        var sFlag = DateUtils.compareTime(sDate, sDate.substring(0, 4) + "-03-01");
        if (sFlag == 1) {
            s = parseInt(sDate.substring(0, 4)) + 1;
        } else if (sFlag == -1) {
        } else if (sFlag == 0) {
            s = parseInt(sDate.substring(0, 4)) + 1;
        }

        var eFlag = DateUtils.compareTime(eDate, eDate.substring(0, 4) + "-02-28");
        if (eFlag == 1) {
        } else if (eFlag == -1) {
            e = parseInt(eDate.substring(0, 4)) - 1;
        } else if (eFlag == 0) {
            e = parseInt(eDate.substring(0, 4)) - 1;
        }


        /*if (sm > 2) {
            s = parseInt(sDate.substring(0, 4)) + 1;
        } else {
            s = parseInt(sDate.substring(0, 4)) - 1;
        }
        if (em < 2) {
            e = parseInt(eDate.substring(0, 4)) - 1;
        } else {
            e = parseInt(eDate.substring(0, 4)) + 1;
        }*/
        /*if (DateUtils.isLeapYear(sDate.substring(0, 4)) == true && parseInt(sDate.substring(5, 7)) < 2) {
            s = parseInt(sDate.substring(0, 4));
        }
        if (DateUtils.isLeapYear(eDate.substring(0, 4)) == true && parseInt(eDate.substring(5, 7)) > 2) {
            e = parseInt(eDate.substring(0, 4));
        }*/
        for (var i = s; i <= e; i++) {
            var flag = DateUtils.isLeapYear(i);
            if (flag) {
                leap++;
            }
        }

        return Math.ceil((days - leap) / 365);
    },

    /**
     * 获取上一个月
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getPreMonth: function (date) {
        var arr = date.split('-');
        var year = arr[0]; //获取当前日期的年份
        var month = arr[1]; //获取当前日期的月份
        var day = arr[2]; //获取当前日期的日
        var days = new Date(year, month, 0);
        days = days.getDate(); //获取当前日期中月的天数
        var year2 = year;
        var month2 = parseInt(month) - 1;
        if (month2 == 0) {
            year2 = parseInt(year2) - 1;
            month2 = 12;
        }
        var day2 = day;
        var days2 = new Date(year2, month2, 0);
        days2 = days2.getDate();
        if (day2 > days2) {
            day2 = days2;
        }
        if (month2 < 10) {
            month2 = '0' + month2;
        }
        var t2 = year2 + '-' + month2 + '-' + day2;
        return t2;
    },

    /**
     * 获取下一个月
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getNextMonth: function (date) {
        var arr = date.split('-');
        var year = arr[0]; //获取当前日期的年份
        var month = arr[1]; //获取当前日期的月份
        var day = arr[2]; //获取当前日期的日
        var days = new Date(year, month, 0);
        days = days.getDate(); //获取当前日期中的月的天数
        var year2 = year;
        var month2 = parseInt(month) + 1;
        if (month2 == 13) {
            year2 = parseInt(year2) + 1;
            month2 = 1;
        }
        var day2 = day;
        var days2 = new Date(year2, month2, 0);
        days2 = days2.getDate();
        if (day2 > days2) {
            day2 = days2;
        }
        if (month2 < 10) {
            month2 = '0' + month2;
        }

        var t2 = year2 + '-' + month2 + '-' + day2;
        return t2;
    },
    /**
     * 获取两个日期间隔的月数
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    getSpacingMonths: function (d1, d2) {
        var m1 = parseInt(d1.split("-")[1].replace(/^0+/, "")) + parseInt(d1.split("-")[0]) * 12;
        var m2 = parseInt(d2.split("-")[1].replace(/^0+/, "")) + parseInt(d2.split("-")[0]) * 12;
        return m2 - m1;
    },

    /**
     * 日期加N个月
     *
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    addMoth: function (d, m) {
        var ds = d.split('-'), _d = ds[2] - 0;
        var nextM = new Date(ds[0], ds[1] - 1 + m + 1, 0);
        var max = nextM.getDate();
        d = new Date(ds[0], ds[1] - 1 + m, _d > max ? max : _d);
        return d.toLocaleDateString().match(/\d+/g).join('-')
    },

    firstDate: function () {
        var date=new Date();
        date.setDate(1);
        return DateUtils.formatDate(date);


    },

    lastDate: function () {
        var date=new Date();
        var currentMonth=date.getMonth();
        var nextMonth=++currentMonth;
        var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
        var oneDay=1000*60*60*24;
        return  DateUtils.formatDate(new Date(nextMonthFirstDay-oneDay));
    },
    formatDate:  function (time){
    var date = new Date(time);

    var year = date.getFullYear(),
        month = date.getMonth()+1,//月份是从0开始的
        day = date.getDate(),
        hour = date.getHours(),
        min = date.getMinutes(),
        sec = date.getSeconds();
    var preArr = Array.apply(null,Array(10)).map(function(elem, index) {
        return '0'+index;
    });////开个长度为10的数组 格式为 00 01 02 03

    var newTime = year + '-' +
        (preArr[month]||month) + '-' +
        (preArr[day]||day)

    return newTime;
}
};